package com.ikan.study;

import com.ikan.study.model.AnnotationUser;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import java.io.Serializable;

/**
 * 测试注解方式执行
 *
 * @author fanyusong@126.com
 * @date 2024/2/11 18:19
 */
@Slf4j
public class MainAnnotation {
    private static final SessionFactory sessionFactory;

    // 创建sessionFactory对象
    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure()
                    .addAnnotatedClass(AnnotationUser.class);

            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static void main(String[] args) {
        Session session = sessionFactory.openSession();
        try {
            AnnotationUser user = new AnnotationUser();
            user.setId(18);
            user.setName("monster");
            Serializable userId = session.save(user);
            AnnotationUser annotation = (AnnotationUser) session.get(AnnotationUser.class, userId);
            log.info("【注解方式】用户的姓名：{}", annotation.getName());
            session.close();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
            if (sessionFactory != null && !sessionFactory.isClosed()) {
                sessionFactory.close();
            }
        }
    }
}
